package com.fengwk.support.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.fengwk.support.exception.BaseException;

/**
 * 文件扩展名工具
 */
public final class FileExtensionUtils {

    public static final String EXTENTSION_CHARACTER = ".";
    public static final String[] IMAGES = {"jpg", "jpeg", "png", "gif", "bmp"};
    public static final String[] OFFICES = {"doc", "docx", "xls", "xlsx", "ppt", "txt"};
    public static final Set<String> IMAGE_SET = new HashSet<String>();
    public static final Set<String> OFFICE_SET = new HashSet<String>();
    public static final Set<String> ALL_SET = new HashSet<String>();

    static {
        IMAGE_SET.addAll(Arrays.asList(IMAGES));
        OFFICE_SET.addAll(Arrays.asList(OFFICES));
        ALL_SET.addAll(IMAGE_SET);
        ALL_SET.addAll(OFFICE_SET);
    }
    
    private FileExtensionUtils() {
    	throw new BaseException("can not instance " + getClass());
    }
    
    /**
     * 图片类型后缀校验
     * 
     * @param fileName
     * @return
     */
    public static boolean isImageFile(String fileName){
        return FileExtensionUtils.validateFileExtension(fileName, IMAGE_SET);
    }
    
    /**
     * Office后缀校验方法
     * 
     * @param fileName
     * @return
     */
    public static boolean isOfficeFile(String fileName){
        return FileExtensionUtils.validateFileExtension(fileName, OFFICE_SET);
    }
    
    /**
     * 后缀校验方法
     * 
     * @param fileName
     * @param extSets 后缀集合
     * @return
     */
    public static boolean validateFileExtension(String fileName, Collection<String> exts){
        if(fileName == null || "".equals(fileName.trim()) || fileName.lastIndexOf(EXTENTSION_CHARACTER) == -1){
            return false;
        }
        return matchExtension(fileName.substring(fileName.lastIndexOf(EXTENTSION_CHARACTER)+1).toLowerCase(), exts);
    }
    
    /**
     * 后缀匹配
     * 
     * @param extension
     * @param exts
     * @return
     */
    public static boolean matchExtension(String extension, Collection<String> exts){
    	if(StringUtils.isBlank(extension))
    		return false;
    	return exts.contains(extension);
    }

    /**
     * 后缀分离
     * 
     * @param fileName
     * @return String[0]为分离的文件名称,String[1]为分离的后缀,分离失败返回null
     */
    public static String[] split(String fileName) {
    	if(StringUtils.isBlank(fileName) || fileName.lastIndexOf(EXTENTSION_CHARACTER) == -1) {
    		return null;
    	}
    	String[] res = new String[2];
    	res[1] = fileName.substring(fileName.lastIndexOf(EXTENTSION_CHARACTER) + 1).toLowerCase();
    	res[0] = StringUtils.trimSuffix(fileName, "\\.[^\\.]+");
    	return res;
    }
    
}
